using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
using BBX.Common;
using BBX.Config;
using BBX.Entity;
using BBX.Forum;
using BBX.Web.UI;

namespace BBX.Web
{
    public class buytopic : TopicPage
	{
        public IList<Post> lastpostlist;
		public IList<PaymentLog> paymentloglist;
		public UserExtcreditsInfo userextcreditsinfo = Scoresets.GetScoreSet(Scoresets.GetTopicAttachCreditsTrans());
		public Int32 buyers;
		public Int32 showpayments = DNTRequest.GetInt("showpayments", 0);
		public Int32 buyit = DNTRequest.GetInt("buyit", 0);
		public Int32 topicprice;
		public Single netamount;
		public Int32 maxincpertopic = Scoresets.GetMaxIncPerTopic();
		public Int32 maxchargespan = Scoresets.GetMaxChargeSpan();
		public Single creditstax = Scoresets.GetCreditsTax() * 100f;
		public Int32 price;
		public Single userlastprice;
		public Int32 expirehours;
		public Post postinfo;
		public String postmessage = "";
		public static Regex r = new Regex("\\s*\\[free\\][\\n\\r]*([\\s\\S]+?)[\\n\\r]*\\[\\/free\\]\\s*", RegexOptions.IgnoreCase);
		private Int32 pageSize = GeneralConfigInfo.Current.Tpp;

		protected override void OnInit(EventArgs e)
		{
			if (!SetTopicInfo())
			{
                topic = new Topic();
                forum = new XForum();
				//return;
			}
			base.OnInit(e);
		}

		protected override void ShowPage()
		{
			if (topic.ID == 0) return;

            pagetitle = topic.Title.Trim();
			if (!String.IsNullOrEmpty(forum.Password) && Utils.MD5(forum.Password) != ForumUtils.GetCookie("forum" + forum.Fid + "password"))
			{
				base.AddErrLine("本版块被管理员设置了密码");
				base.Response.Redirect(string.Format("{0}showforum-{1}{2}", BaseConfigs.GetForumPath, forum.Fid, config.Extname), true);
				return;
			}
			if (!UserAuthority.VisitAuthority(forum, usergroupinfo, userid, ref this.msg))
			{
				base.AddErrLine(this.msg);
				return;
			}
            postinfo = Post.FindByTid(topicid);
            var msg = postinfo.Message;
			if (msg.ToLower().Contains("[free]") || msg.ToLower().Contains("[/free]"))
			{
				var match = buytopic.r.Match(msg);
				while (match.Success)
				{
                    Object obj = postmessage;
                    postmessage = obj + "<br /><div class=\"msgheader\">免费内容:</div><div class=\"msgborder\">" + match.Groups[1] + "</div><br />";
					match = match.NextMatch();
				}
			}
            topicprice = topic.Price;
			if (topic.Price > 0)
			{
                price = topic.Price;
                expirehours = (Int32)(DateTime.Now - topic.PostDateTime.AddHours(maxchargespan)).TotalHours;
				if (PaymentLog.IsBuyer(topicid, userid) || (expirehours > 0 && maxchargespan != 0))
				{
                    price = -1;
				}
				else
				{
                    expirehours = Math.Abs(expirehours);
				}
			}
            netamount = (Single)topicprice - (Single)topicprice * creditstax / 100f;
			if (topicprice > maxincpertopic)
			{
                netamount = (Single)maxincpertopic - (Single)maxincpertopic * creditstax / 100f;
			}
			if (price != -1)
			{
				var userInfo = Users.GetUserInfo(userid);
				if (buyit == 1 && !CheckUserExtCredit(userInfo))
				{
					return;
				}
                userlastprice = Users.GetUserExtCredit(userInfo, Scoresets.GetTopicAttachCreditsTrans()) - (Single)topic.Price;
			}
			if (!ispost)
			{
                buyers = PaymentLog.GetPaymentLogByTidCount(topic.ID);
				if (showpayments == 1)
				{
                    pagecount = ((buyers % pageSize == 0) ? (buyers / pageSize) : (buyers / pageSize + 1));
                    pagecount = ((pagecount == 0) ? 1 : pagecount);
                    pageid = ((pageid < 1) ? 1 : pageid);
                    pageid = ((pageid > pagecount) ? pagecount : pageid);
                    paymentloglist = PaymentLog.GetPaymentLogByTid(pageSize, pageid, topic.ID);
				}
                var hide = (topic.Hide == 1) ? topic.Hide : 0;
				if (Post.IsReplier(topicid, userid))
				{
					hide = -1;
				}
                lastpostlist = Posts.GetPagedLastPost(GetPostPramsInfo(hide));
				return;
			}
            var num = PaymentLog.BuyTopic(userid, topic.ID, topic.PosterID, topic.Price, netamount);
			if (num > 0)
			{
				base.SetUrl(base.ShowTopicAspxRewrite(topic.ID, 0));
				base.SetMetaRefresh();
				base.SetShowBackLink(false);
				base.MsgForward("buytopic_succeed");
				base.AddMsgLine("购买主题成功,返回该主题");
				return;
			}
			base.SetBackLink(base.ShowForumAspxRewrite(topic.Fid, 0));
			if (num == -1)
			{
				base.AddErrLine("对不起,您的账户余额少于交易额,无法进行交易");
				return;
			}
			if (num == -2)
			{
				base.AddErrLine("您无权购买本主题");
				return;
			}
			base.AddErrLine("未知原因,交易无法进行,给您带来的不方便我们很抱歉");
		}

		private Boolean SetTopicInfo()
		{
			if (userid < 0)
			{
				base.AddErrLine("您还没有登录，请登录后再操作");
                needlogin = true;
				return false;
			}
			if (topicid == -1)
			{
				base.AddErrLine("无效的主题ID");
				return false;
			}
            //this.topic = Topics.GetTopicInfo(this.topicid);
            topic = Topic.FindByID(topicid);
			if (topic == null)
			{
				base.AddErrLine("不存在的主题ID");
				return false;
			}
			if (topic.DisplayOrder == -1 || topic.DisplayOrder == -2)
			{
				base.AddErrLine("此主题已被删除或未经审核！");
				return false;
			}
            forum = Forums.GetForumInfo(topic.Fid);
			if (forum == null)
			{
				base.AddErrLine("主题对应版块不存在！");
				return false;
			}
			if (((topic.PosterID == userid || ismoder == 1) && String.IsNullOrEmpty(DNTRequest.GetString("showpayments"))) || topic.Price <= 0)
			{
				HttpContext.Current.Response.Redirect(BaseConfigs.GetForumPath + base.ShowTopicAspxRewrite(topic.ID, 0));
				return false;
			}
			if (topic.ReadPerm > usergroupinfo.Readaccess && topic.PosterID != userid && useradminid != 1 && ismoder != 1)
			{
				base.AddErrLine(string.Format("本主题阅读权限为: {0}, 您当前的身份 \"{1}\" 阅读权限不够", topic.ReadPerm.ToString(), usergroupinfo.GroupTitle));
				return false;
			}
			return true;
		}

		private PostpramsInfo GetPostPramsInfo(Int32 hide)
		{
			var postpramsInfo = new PostpramsInfo();
			postpramsInfo.Fid = forum.Fid;
			postpramsInfo.Tid = topicid;
			postpramsInfo.Jammer = forum.Jammer;
			postpramsInfo.Pagesize = 5;
			postpramsInfo.Pageindex = 1;
			postpramsInfo.Getattachperm = forum.Getattachperm;
			postpramsInfo.Usergroupid = usergroupid;
			postpramsInfo.Attachimgpost = config.Attachimgpost;
			postpramsInfo.Showattachmentpath = config.Showattachmentpath;
			postpramsInfo.Hide = hide;
			postpramsInfo.Price = price;
			postpramsInfo.Ubbmode = false;
			postpramsInfo.Showimages = forum.Allowimgcode;
			postpramsInfo.Smiliesinfo = Smilies.GetSmiliesListWithInfo();
			postpramsInfo.Customeditorbuttoninfo = Editors.GetCustomEditButtonListWithInfo();
			postpramsInfo.Smiliesmax = config.Smiliesmax;
			postpramsInfo.Bbcodemode = config.Bbcodemode;
			postpramsInfo.CurrentUserid = userid;
			var userInfo = Users.GetUserInfo(postpramsInfo.CurrentUserid);
			postpramsInfo.Usercredits = ((userInfo == null) ? 0 : userInfo.Credits);
			return postpramsInfo;
		}

		public Boolean CheckUserExtCredit(User userInfo)
		{
			if (userInfo == null)
			{
				base.AddErrLine("您无权购买本主题");
                needlogin = true;
				return false;
			}
			if (Users.GetUserExtCredit(userInfo, Scoresets.GetTopicAttachCreditsTrans()) < (Single)topic.Price)
			{
                var text = "";
				if (EPayments.IsOpenEPayments())
				{
					text = "<br/><span><a href=\"usercpcreditspay.aspx\">点击充值积分</a></span>";
				}
				base.AddErrLine(string.Format("对不起,您的账户余额 <span class=\"bold\">{0} {1}{2}</span> 交易额为 {3}{2} ,无法进行交易.{4}", new Object[]
                {
                    Scoresets.GetValidScoreName()[Scoresets.GetTopicAttachCreditsTrans()],
                    Users.GetUserExtCredit(userInfo, Scoresets.GetTopicAttachCreditsTrans()),
                    Scoresets.GetValidScoreUnit()[Scoresets.GetTopicAttachCreditsTrans()],
                    topic.Price,
                    text
                }));
				return false;
			}
			return true;
		}
	}
}